import React, { useRef, useEffect, useState, forwardRef, useImperativeHandle } from 'react';
import { Button, Space, Tooltip, Switch } from 'antd';
import {
  ZoomInOutlined,
  ZoomOutOutlined,
  ReloadOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  FullscreenOutlined,
  EyeOutlined,
  PictureOutlined
} from '@ant-design/icons';
import * as d3 from 'd3';

/**
 * 通用图谱可视化组件
 * 使用 D3.js 实现，替代 Graphin
 */
const GraphinVisualization = forwardRef(({ 
  nodes = [], 
  edges = [], 
  layout = 'force',
  onNodeClick,
  onEdgeClick,
  onNodePositionUpdate,
  editable = false,
  width = '100%',
  height = 500,
  zoom = 1,
  animationSpeed = 0.3,
  isSimulationRunning = true,
  isFullscreen = false,
  onToggleFullscreen
}, ref) => {
  const svgRef = useRef(null);
  const containerRef = useRef(null);
  const simulationRef = useRef(null);
  
  const [currentZoom, setCurrentZoom] = useState(zoom);
  const [isRunning, setIsRunning] = useState(isSimulationRunning);
  const [showMiniMap, setShowMiniMap] = useState(false);
  const [showFishEye, setShowFishEye] = useState(false);

  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    centerGraph: () => {
      if (!svgRef.current) return;
      
      const svg = d3.select(svgRef.current);
      const containerWidth = containerRef.current?.clientWidth || 800;
      const containerHeight = containerRef.current?.clientHeight || 500;
      
      svg.transition()
        .duration(750)
        .call(
          d3.zoom().transform,
          d3.zoomIdentity
            .translate(containerWidth / 2, containerHeight / 2)
            .scale(1)
        );
      setCurrentZoom(1);
    },
    
    startSimulation: (speed) => {
      if (simulationRef.current) {
        simulationRef.current.alphaTarget(speed || animationSpeed).restart();
        setIsRunning(true);
      }
    },
    
    pauseSimulation: () => {
      if (simulationRef.current) {
        simulationRef.current.alphaTarget(0).stop();
        setIsRunning(false);
      }
    },
    
    updateAnimationSpeed: (speed) => {
      if (simulationRef.current && isRunning) {
        simulationRef.current.alphaTarget(speed).restart();
      }
    },
    
    exportImage: () => {
      if (!svgRef.current) return;
      
      const svg = svgRef.current;
      const serializer = new XMLSerializer();
      const source = serializer.serializeToString(svg);
      
      const canvas = document.createElement('canvas');
      const context = canvas.getContext('2d');
      const img = new Image();
      
      img.onload = () => {
        canvas.width = img.width;
        canvas.height = img.height;
        context.drawImage(img, 0, 0);
        
        const link = document.createElement('a');
        link.download = 'graph.png';
        link.href = canvas.toDataURL();
        link.click();
      };
      
      img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(source)));
    },
    
    getGraph: () => {
      return {
        nodes: nodes,
        edges: edges,
        simulation: simulationRef.current
      };
    }
  }));

  // 主渲染函数
  useEffect(() => {
    if (!svgRef.current || !nodes || nodes.length === 0) return;

    const svg = d3.select(svgRef.current);
    svg.selectAll('*').remove();

    const container = svg.append('g').attr('class', 'graph-container');
    
    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;

    // 创建缩放行为
    const zoomBehavior = d3.zoom()
      .scaleExtent([0.1, 4])
      .on('zoom', (event) => {
        const transform = event.transform;
        container.attr('transform', `translate(${transform.x}, ${transform.y}) scale(${transform.k})`);
        setCurrentZoom(transform.k);
      });

    svg.call(zoomBehavior);

    // 确保节点和边数据有效
    const validNodes = nodes.filter(node => node && node.id);
    const validEdges = edges.filter(edge => 
      edge && edge.source && edge.target && 
      validNodes.some(n => n.id === (typeof edge.source === 'object' ? edge.source.id : edge.source)) &&
      validNodes.some(n => n.id === (typeof edge.target === 'object' ? edge.target.id : edge.target))
    );

    // 创建力导向模拟
    const simulation = d3.forceSimulation(validNodes)
      .force('link', d3.forceLink(validEdges).id(d => d.id).distance(100))
      .force('charge', d3.forceManyBody().strength(-300))
      .force('center', d3.forceCenter(containerWidth / 2, containerHeight / 2))
      .force('collision', d3.forceCollide().radius(30));

    simulationRef.current = simulation;

    // 绘制连接线
    const links = container.selectAll('.link')
      .data(validEdges)
      .enter()
      .append('line')
      .attr('class', 'link')
      .style('stroke', '#999')
      .style('stroke-width', 2)
      .style('opacity', 0.6);

    // 绘制节点
    const nodeGroups = container.selectAll('.node')
      .data(validNodes)
      .enter()
      .append('g')
      .attr('class', 'node')
      .style('cursor', editable ? 'pointer' : 'default');

    // 节点圆圈
    nodeGroups.append('circle')
      .attr('r', d => d.size || 20)
      .style('fill', d => d.color || '#1890ff')
      .style('stroke', '#fff')
      .style('stroke-width', 2);

    // 节点标签
    nodeGroups.append('text')
      .attr('dy', '0.35em')
      .attr('text-anchor', 'middle')
      .style('fill', '#fff')
      .style('font-size', '12px')
      .style('font-weight', 'bold')
      .text(d => d.label || d.id);

    // 节点点击事件
    if (onNodeClick) {
      nodeGroups.on('click', function(event, d) {
        onNodeClick(d);
      });
    }

    // 节点拖拽（如果可编辑）
    if (editable) {
      const drag = d3.drag()
        .on('start', function(event, d) {
          if (!event.active) simulation.alphaTarget(0.3).restart();
          d.fx = d.x;
          d.fy = d.y;
        })
        .on('drag', function(event, d) {
          d.fx = event.x;
          d.fy = event.y;
        })
        .on('end', function(event, d) {
          if (!event.active) simulation.alphaTarget(0);
          d.fx = null;
          d.fy = null;
          
          if (onNodePositionUpdate) {
            onNodePositionUpdate(d.id, d.x, d.y);
          }
        });

      nodeGroups.call(drag);
    }

    // 更新位置
    simulation.on('tick', () => {
      links
        .attr('x1', d => d.source.x)
        .attr('y1', d => d.source.y)
        .attr('x2', d => d.target.x)
        .attr('y2', d => d.target.y);

      nodeGroups
        .attr('transform', d => `translate(${d.x}, ${d.y})`);
    });

    // 设置初始状态
    if (!isRunning) {
      simulation.alphaTarget(0).stop();
    } else {
      simulation.alphaTarget(animationSpeed);
    }

    return () => {
      if (simulation) {
        simulation.stop();
      }
    };
  }, [nodes, edges, layout, isRunning, animationSpeed, editable, onNodeClick, onNodePositionUpdate]);

  // 控制函数
  const handleZoomIn = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom * 1.2)
    );
    setCurrentZoom(prev => prev * 1.2);
  };

  const handleZoomOut = () => {
    const svg = d3.select(svgRef.current);
    svg.transition().call(
      d3.zoom().transform,
      d3.zoomIdentity.scale(currentZoom / 1.2)
    );
    setCurrentZoom(prev => prev / 1.2);
  };

  const handleReset = () => {
    const svg = d3.select(svgRef.current);
    const containerWidth = containerRef.current?.clientWidth || 800;
    const containerHeight = containerRef.current?.clientHeight || 500;
    
    svg.transition()
      .duration(750)
      .call(
        d3.zoom().transform,
        d3.zoomIdentity
          .translate(containerWidth / 2, containerHeight / 2)
          .scale(1)
      );
    setCurrentZoom(1);
  };

  const toggleSimulation = () => {
    if (simulationRef.current) {
      if (isRunning) {
        simulationRef.current.alphaTarget(0).stop();
        setIsRunning(false);
      } else {
        simulationRef.current.alphaTarget(animationSpeed).restart();
        setIsRunning(true);
      }
    }
  };

  return (
    <div style={{ 
      position: 'relative', 
      width, 
      height, 
      border: '1px solid #d9d9d9', 
      borderRadius: '8px', 
      overflow: 'hidden',
      background: '#fff'
    }}>
      {/* 工具栏 */}
      <div style={{
        position: 'absolute',
        top: '8px',
        right: '8px',
        zIndex: 15,
        background: 'rgba(255, 255, 255, 0.95)',
        borderRadius: '6px',
        padding: '8px',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
        border: '1px solid #e8e8e8'
      }}>
        <Space size="small">
          <Tooltip title="放大">
            <Button size="small" icon={<ZoomInOutlined />} onClick={handleZoomIn} />
          </Tooltip>
          <Tooltip title="缩小">
            <Button size="small" icon={<ZoomOutOutlined />} onClick={handleZoomOut} />
          </Tooltip>
          <Tooltip title="重置视图">
            <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} />
          </Tooltip>
          <Tooltip title={isRunning ? '暂停动画' : '播放动画'}>
            <Button 
              size="small" 
              icon={isRunning ? <PauseCircleOutlined /> : <PlayCircleOutlined />} 
              onClick={toggleSimulation}
              type={isRunning ? 'default' : 'primary'}
            />
          </Tooltip>
          <Tooltip title="鱼眼视图">
            <Button 
              size="small" 
              icon={<EyeOutlined />} 
              onClick={() => setShowFishEye(!showFishEye)}
              type={showFishEye ? 'primary' : 'default'}
            />
          </Tooltip>
          <Tooltip title="小地图">
            <Button 
              size="small" 
              icon={<PictureOutlined />} 
              onClick={() => setShowMiniMap(!showMiniMap)}
              type={showMiniMap ? 'primary' : 'default'}
            />
          </Tooltip>
          {onToggleFullscreen && (
            <Tooltip title={isFullscreen ? '退出全屏' : '全屏显示'}>
              <Button 
                size="small" 
                icon={<FullscreenOutlined />} 
                onClick={onToggleFullscreen}
                type={isFullscreen ? 'primary' : 'default'}
              />
            </Tooltip>
          )}
        </Space>
      </div>

      {/* SVG 画布 */}
      <div ref={containerRef} style={{ width: '100%', height: '100%' }}>
        <svg
          ref={svgRef}
          width="100%"
          height="100%"
          style={{ display: 'block' }}
        />
      </div>

      {/* 状态指示器 */}
      <div style={{
        position: 'absolute',
        bottom: '8px',
        left: '8px',
        background: 'rgba(0,0,0,0.7)',
        color: 'white',
        padding: '4px 8px',
        borderRadius: '4px',
        fontSize: '12px'
      }}>
        <Space size="small">
          {editable && (
            <>
              <span style={{ color: '#1677ff' }}>编辑模式</span>
              <span>|</span>
            </>
          )}
          <span>缩放: {Math.round(currentZoom * 100)}%</span>
          <span>|</span>
          <span>节点: {nodes.length}</span>
          <span>|</span>
          <span>边: {edges.length}</span>
          <span>|</span>
          <span>布局: {layout}</span>
          <span>|</span>
          <span style={{ color: isRunning ? '#52c41a' : '#ff4d4f' }}>
            {isRunning ? '运行中' : '已停止'}
          </span>
        </Space>
      </div>

      {/* 小地图 */}
      {showMiniMap && (
        <div style={{
          position: 'absolute',
          bottom: '50px',
          right: '8px',
          width: '200px',
          height: '150px',
          background: 'rgba(255,255,255,0.9)',
          border: '1px solid #d9d9d9',
          borderRadius: '4px',
          zIndex: 10
        }}>
          <div style={{
            padding: '4px',
            fontSize: '12px',
            fontWeight: 'bold',
            borderBottom: '1px solid #f0f0f0'
          }}>
            小地图
          </div>
          <div style={{
            width: '100%',
            height: 'calc(100% - 30px)',
            background: '#f8f8f8',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '11px',
            color: '#999'
          }}>
            小地图功能开发中...
          </div>
        </div>
      )}

      {/* 鱼眼视图 */}
      {showFishEye && (
        <div style={{
          position: 'absolute',
          top: '50px',
          left: '8px',
          width: '150px',
          height: '150px',
          background: 'rgba(255,255,255,0.9)',
          border: '1px solid #d9d9d9',
          borderRadius: '50%',
          zIndex: 10,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontSize: '11px',
          color: '#999'
        }}>
          鱼眼视图开发中...
        </div>
      )}

      {/* 空数据提示 */}
      {nodes.length === 0 && (
        <div style={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          textAlign: 'center',
          color: '#999'
        }}>
          <p>暂无数据</p>
          <p style={{ fontSize: '12px' }}>请添加节点和关系来构建图谱</p>
        </div>
      )}
    </div>
  );
});

GraphinVisualization.displayName = 'GraphinVisualization';

export default GraphinVisualization;
